using AutoMapper;
using Process.Domain.DTO.InputDTO;
using Process.Domain.DTO.OutDTO;
using Process.Domain.Entities;
using Process.Infrastructure.Repositories;
using Process.Result;
using SqlSugar;
using System.Text.Json;

namespace Process.Application.Services
{
    public class OperationAppService<T> : IOperationAppService<T> where T : BaseEntity
    {
        private readonly IProcessRepository<OperationModel> _repository;
        private readonly IMapper _mapper;

        public OperationAppService(
            IProcessRepository<OperationModel> repository,
            IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加工艺（使用DTO）
        /// </summary>
        /// <param name="operationDTO">工艺数据传输对象</param>
        /// <returns>API结果</returns>
        public ApiResult<int> AddOperation(AddOperationDTO operationDTO)
        {
            // 验证参数是否为空
            if (operationDTO == null)
            {
                return new ApiResult<int>
                {
                    Success = ResultCode.Fail,
                    Message = "参数不能为空",
                    Data = 0
                };
            }

            try
            {
                // 使用AutoMapper将DTO映射为实体
                var operationModel = _mapper.Map<OperationModel>(operationDTO);

                // 生成雪花ID
                operationModel.Id = GenerateSnowflakeId();
                string ss = Guid.NewGuid().ToString();
                operationModel.OperationCode = ss;
                // 设置创建时间和创建人
                operationModel.CreatedAt = DateTime.Now;
                operationModel.CreatedBy = "System"; // 可以从认证上下文中获取当前用户

                // 调用仓储添加数据
                int result = _repository.Create(operationModel);

                return new ApiResult<int>
                {
                    Success = result > 0 ? ResultCode.Success : ResultCode.Fail,
                    Message = result > 0 ? "添加成功" : "添加失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Success = ResultCode.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除工艺
        /// </summary>
        /// <param name="Id">工艺ID</param>
        /// <returns>API结果</returns>
        public ApiResult<int> DeleteOperation(long Id)
        {
            ApiResult<int> api = new ApiResult<int>();
            var data = _repository.GetModel(Id);
            data.IsDeleted = true;
            var result = _repository.Update(data);
            return new ApiResult<int>
            {
                Success = result > 0 ? ResultCode.Success : ResultCode.Fail,
                Message = result > 0 ? "删除成功" : "删除失败",
                Data = result
            };
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns>封装响应类</returns>
        public Apipaging<PagingOperationDTO> PagingOperation(PagingOperationInput input)
        {
            Apipaging<PagingOperationDTO> api = new Apipaging<PagingOperationDTO>();
            var list = _repository.GetValue().Where(x => x.IsDeleted == false);
            if (!string.IsNullOrEmpty(input.OperationName))
            {
                list = list.Where(x => x.OperationName.Equals(input.OperationName));
            }
            if (!string.IsNullOrEmpty(input.OperationCode))
            {
                list = list.Where(x => x.OperationCode.Equals(input.OperationCode));
            }
            api.TotalCount = list.Count();
            api.TotalPages = (int)Math.Ceiling(api.TotalCount * 1.0 / input.PagingSize);
            var data = list.OrderBy(x => x.Id).Skip((input.PagingIndex - 1) * input.PagingSize).Take(input.PagingSize).ToList();
            api.PagingData = _mapper.Map<List<PagingOperationDTO>>(data);

            return api;
        }
        //显示所有工艺
        public ApiResult<List<ShowOperationDTO>> ShowOperation()
        {
            ApiResult<List<ShowOperationDTO>> api = new ApiResult<List<ShowOperationDTO>>();
            var list = _repository.GetValue().Where(x => x.IsDeleted == false);
            api.Data=_mapper.Map<List<ShowOperationDTO>>(list);
            return api;
        }

        /// <summary>
        /// 修改工艺
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns>API结果</returns>
        public ApiResult<int> UpdateOperation(UpdateOperationInput input)
        {
            ApiResult<int> api = new ApiResult<int>();
            var operation = _repository.GetModel(input.Id);
            var data = _mapper.Map(input, operation);
            var result = _repository.Update(data);
            return new ApiResult<int>
            {
                Success = result > 0 ? ResultCode.Success : ResultCode.Fail,
                Message = result > 0 ? "修改成功" : "修改失败",
                Data = result
            };
        }

        /// <summary>
        /// 生成雪花ID
        /// </summary>
        /// <returns>唯一ID</returns>
        private long GenerateSnowflakeId()
        {
            // 简化版雪花ID实现
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            long machineId = 1; // 机器ID
            long sequence = new Random().Next(0, 4095); // 序列号

            return ((timestamp - 1288834974657L) << 22) | (machineId << 12) | sequence;
        }

       
    }
} 